<template>
  <div>
    <el-dialog :title="title" :visible.sync="visible" width="60%" append-to-body custom-class="import-dialog">
      <div class="app-container">
        <!--    展示区域    -->
        <div class="show-container">
          <el-tag
            v-for="(item, index) in selectedList"
            :key="index"
            closable
            @close="handleRemove(item)"
          >
            {{ item[labelKey] ? item[labelKey] : item.phonenumber }}
          </el-tag>
        </div>
        <!--    选择区域    -->
        <div class="select-container">
          <div class="select-container__header">
            <el-tabs v-model="activeName" @tab-click="handleClick"
                     v-if="['1', '2', '3'].includes(data.pushChannel)||data.ordinaryMessageType === '1'"
            >
              <el-tab-pane label="部门" name="department">
                <div class="select-container__header__label">{{ data.tenantName }}</div>
              </el-tab-pane>
              <el-tab-pane label="角色" name="role">
                <div class="select-container__header__label">角色组</div>
              </el-tab-pane>
              <el-tab-pane label="搜索" name="search">
                <div class="select-container__header__search">
                  <el-form :model="userParams" ref="userParams" size="small" :inline="true" label-width="68px">
                    <el-form-item label="用户名" prop="userName">
                      <el-input
                        v-model="userParams.userName"
                        placeholder="请输入用户名"
                        clearable
                        @keyup.enter.native="handleQuery"
                      />
                    </el-form-item>
                    <el-form-item label="手机号" prop="phonenumber">
                      <el-input
                        v-model="userParams.phonenumber"
                        placeholder="请输入手机号"
                        clearable
                        @keyup.enter.native="handleQuery"
                      />
                    </el-form-item>
                    <el-form-item>
                      <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                      <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
                    </el-form-item>
                  </el-form>
                </div>
              </el-tab-pane>
            </el-tabs>
            <div class="select-container__header__search" v-if="['4'].includes(data.pushChannel)">
              <el-form :model="userParams" ref="userParams" size="small" :inline="true" label-width="68px">
                <el-form-item label="用户名" prop="userName">
                  <el-input
                    v-model="userParams.userName"
                    placeholder="请输入用户名"
                    clearable
                    @keyup.enter.native="handleQuery"
                  />
                </el-form-item>
                <el-form-item label="手机号" prop="phonenumber">
                  <el-input
                    v-model="userParams.phonenumber"
                    placeholder="请输入手机号"
                    clearable
                    @keyup.enter.native="handleQuery"
                  />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                  <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
                </el-form-item>
              </el-form>
            </div>
          </div>
          <div class="select-container__body">
            <div class="select-container__body__left"
                 v-if="(activeName === 'department' || activeName === 'role') && (['1', '2', '3'].includes(data.pushChannel)||data.ordinaryMessageType === '1')"
            >
              <div class="select-container__body__left__content" v-loading="loadingLeft">
                <div class="select-container__body__left__content__item"
                     :class="{'active': userParams.value === item.value}" v-for="(item, index) in list" :key="index"
                     @click="handleSelectDepartment(item)"
                >
                  {{ item.label }}
                </div>
                <div class="select-container__body__empty" v-if="list.length === 0">
                  <div>
                    <span>暂无数据</span>
                  </div>
                </div>
              </div>
            </div>
            <div class="select-container__body__right">
              <div class="select-container__body__right__header">
                <div class="select-container__body__right__header__left">
                  已选 {{ handleUserListSelected(userList).length }} / {{ userList.length }}
                </div>
                <div class="select-container__body__right__header__right">
                  <el-checkbox :indeterminate="isIndeterminate" v-model="isAll" @change="handleAllChange"
                               :disabled="userList.length === 0"
                  >全选
                  </el-checkbox>
                </div>
              </div>
              <div class="select-container__body__right__content" v-loading="loadingRight">
                <div class="select-container__body__right__content__item" v-for="(item, index) in userList"
                     :key="index"
                >
                  <div class="select-container__body__right__content__item__label"
                       @click.stop="handleSelectUser(item,'click')"
                  >
                    <span v-if="item[labelKey]">{{ item[labelKey] }}</span>
                    <span>({{ item.phonenumber }})</span>
                  </div>
                  <div class="select-container__body__right__content__item__btn">
                    <el-checkbox v-model="item.selected" @change="handleSelectUser(item)"
                                 :key="item[valueKey]"
                    ></el-checkbox>
                  </div>

                </div>
                <div class="select-container__body__empty" v-if="userList.length === 0">
                  <div>
                    <span>暂无数据</span>
                  </div>
                </div>
              </div>
            </div>

          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" @click="submit">确定</el-button>
        <el-button size="small" @click="close">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import { debounce } from '@/utils'
import { listDept } from '@/api/enterprise/dept'
import { roleListByEnterprise } from '@/api/enterprise/role'
import { listUser, listUserConsumer } from '@/api/enterprise/user'

export default {
  props: {
    title: {
      default: '选择用户'
    },
    show: {
      default: false
    },
    // 已选用户
    selectedData: {
      default: () => []
    },
    valueKey: {
      default: 'userId'
    },
    labelKey: {
      default: 'userName'
    },
    data: {}
  },
  dicts: [],
  data() {
    return {
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        templateName: undefined,
        messageHeader: undefined
      },
      // 遮罩层
      loadingLeft: false,
      loadingRight: false,
      // 总条数
      total: 0,
      //列表
      list: [],
      // 用户列表
      userList: [],
      // 选中列表
      selectedList: [],
      // 选中部门
      activeName: 'department',
      // 用户筛选参数
      userParams: {
        tenantId: undefined,
        deptId: undefined,
        roleId: undefined,
        value: undefined,
        userName: undefined, // 用户名
        phonenumber: undefined // 手机号
      }
    }
  },
  computed: {
    visible: {
      get() {
        return this.show
      },
      set(val) {
        this.$emit('update:show', val)
      }
    },
    //已选用户Id
    selectedIds() {
      return this.selectedList.map(item => item[this.valueKey])
    },
    // 当前用户列表中已选的用户
    handleUserListSelected() {
      return (value) => {
        return this.userList.filter(item => item.selected)
      }
    },

    // 是否全选
    isAll: {
      get() {
        return this.userList.length ? this.userList.length === this.handleUserListSelected(this.userList).length : false
      },
      set(val) {

      }
    },
    // 是否半选
    isIndeterminate: {
      get() {
        return !this.isAll && this.handleUserListSelected(this.userList).length !== 0 && this.handleUserListSelected(this.userList).length !== this.userList.length
      },
      set(val) {
      }
    }
  },
  watch: {
    show: {
      handler(newVal) {
        if (newVal) {
          this.init()
        }
      }
    }
  },
  methods: {
    init() {
      this.reset()
      if (['1', '2', '3'].includes(this.data.pushChannel) || this.data.ordinaryMessageType === '1') {
        this.getDeptOrRoleList()
      } else if (['4'].includes(this.data.pushChannel)) {
        this.getConsumerUserList()
      }
    },
    reset() {
      this.activeName = 'department'
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        templateName: undefined,
        messageHeader: undefined
      }
      this.userParams = {
        tenantId: this.data.tenantId,
        deptId: undefined,
        roleId: undefined,
        value: undefined,
        userName: undefined, // 用户名
        phonenumber: undefined // 手机号
      }
      this.list = []
      this.userList = []
      this.selectedList = []

      this.selectedList = [...this.selectedData]

      this.resetForm('queryForm')
    },
    // 点击tab
    handleClick(tab, event) {
      this.activeName = tab.name
      this.userList = []
      this.userParams.value = undefined
      this.userParams.deptId = undefined
      this.userParams.roleId = undefined
      this.userParams.userName = undefined
      this.userParams.phonenumber = undefined
      if (this.activeName === 'search') {
        this.handleQuery()
      } else {
        this.getDeptOrRoleList()
      }

    },
    // 获取部门/角色列表
    getDeptOrRoleList() {
      this.loadingLeft = true
      let apiUrl = listDept
      if (this.activeName === 'department') {
        apiUrl = listDept
      } else if (this.activeName === 'role') {
        apiUrl = roleListByEnterprise
      }
      let params = {
        tenantId: this.data.tenantId
      }
      apiUrl(params).then((response) => {
        this.list = response.data.map(item => {
          return {
            label: this.activeName === 'department' ? item.deptName : item.roleName,
            value: this.activeName === 'department' ? item.deptId : item.roleId,
            ...item
          }
        })
        this.loadingLeft = false
      }).catch((err) => {
        this.loadingLeft = false
        this.list = []
        this.$message.error(err.msg || '获取失败')
      })
    },
    // 获取c端用户列表
    getConsumerUserList() {
      this.loadingRight = true
      let params = {
        tenantId: this.data.tenantId,
        userName: this.userParams.userName,
        userMobile: this.userParams.phonenumber
      }
      listUserConsumer(params).then(response => {
        this.userList = response.data.map(item => {
          return {
            ...item,
            userName: item.userName,
            phonenumber: item.userMobile,
            selected: this.selectedIds.includes(item[this.valueKey])
          }
        })
        this.loadingRight = false
      }).catch(err => {
        this.userList = []
        this.loadingRight = false
        this.$message.error(err.msg || '获取失败')
      })
    },
    // 全选
    handleAllChange(val) {
      let list = this.userList.filter(item => item.selected !== val)
      list.forEach(item => {
        item.selected = val
        this.handleSelectUser(item)
      })
    },
    // 搜索
    handleQuery() {
      this.userParams.tenantId = this.data.tenantId
      if(['4'].includes(this.data.pushChannel)){
        this.getConsumerUserList()
      }else{
        this.getUserList()
      }
    },
    // 重置
    resetQuery() {
      this.userParams.userName = undefined
      this.userParams.phonenumber = undefined
      this.resetForm('userParams')
      this.handleQuery()
    },
    // 获取用户列表
    getUserList() {
      this.loadingRight = true
      let params = this.userParams
      listUser(params).then(response => {
        this.userList = response.data.map(item => {
          return {
            ...item,
            selected: this.selectedIds.includes(item[this.valueKey])
          }
        })
        this.loadingRight = false
      }).catch(err => {
        this.userList = []
        this.loadingRight = false
        this.$message.error(err.msg || '获取失败')
      })
    },
    // 选择部门/角色
    handleSelectDepartment(item) {
      console.log('item', item)
      this.userParams.tenantId = this.data.tenantId
      this.userParams.value = item.value
      if (this.activeName === 'department') {
        this.userParams.deptId = item.deptId
        this.userParams.roleId = undefined
      } else if (this.activeName === 'role') {
        this.userParams.roleId = item.roleId
        this.userParams.deptId = undefined
      }
      this.getUserList()

      // 初始化列表选中状态、全选状态/取消全选状态
      this.$nextTick(() => {

      })
    },
    // 选择用户
    handleSelectUser(data, type = '') {
      console.log('data', data)
      if (type === 'click') {
        data.selected = !data.selected
      }
      let index = this.selectedList.findIndex(item => item[this.valueKey] === data[this.valueKey])
      if (index !== -1) {
        this.selectedList.splice(index, 1)
      } else {
        this.selectedList.push(data)
      }
      this.$forceUpdate()

    },
    // 移除用户
    handleRemove(data) {
      console.log('item', data)
      data.selected = false
      let index = this.selectedList.findIndex(item => item[this.valueKey] === data[this.valueKey])
      if (index !== -1) {
        this.selectedList.splice(index, 1)
      }
    },
    /** 确定 */
    submit: debounce(function() {
      this.$emit('success', [...this.selectedList])
      this.close()

    }, 500, true),
    close() {
      this.reset()
      this.visible = false
    }
  }
}
</script>

<style lang="scss" scoped>
@import "@/assets/styles/dialog.scss";

.show-container {
  padding: 10px;
  border: 1px dashed #ccc;
  margin-bottom: 10px;
  height: 100px;
  overflow-y: auto;

  ::v-deep.el-tag {
    margin-right: 10px;
    margin-bottom: 10px;

    &:last-child {
      margin-right: 0;
      margin-bottom: 0;
    }
  }
}

.select-container {
  padding: 10px;
  border: 1px solid #000;

  .select-container__header {
    .select-container__header__label {
      font-size: 16px;
      font-weight: bold;
      margin-bottom: 10px;
    }
  }


  .select-container__body {
    display: grid;
    height: 300px;
    //grid-template-columns: 1fr 1fr;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));

    .select-container__body__empty {
      text-align: center;
      padding: 10px;
      color: #999;
      font-size: 14px;
      font-weight: bold;
    }

    .select-container__body__left {
      height: 300px;
      display: flex;
      flex-direction: column;
      border-right: 1px solid #ccc;

      .select-container__body__left__content {
        height: 100%;
        overflow-y: auto;

        .select-container__body__left__content__item {
          padding: 10px;
          cursor: pointer;
          transition: background-color 0.3s;
          display: flex;
          justify-content: space-between;
          align-items: center;

          &:hover {
            background-color: #f5f5f5;
            color: #19AFF1;
          }

          &.active {
            background-color: #f5f5f5;
            color: #19AFF1;
          }
        }
      }
    }

    .select-container__body__right {
      height: 300px;
      display: flex;
      flex-direction: column;

      .select-container__body__right__header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 10px;
        border-bottom: 1px solid #ccc;
      }

      .select-container__body__right__content {
        height: 100%;
        overflow-y: auto;

        .select-container__body__right__content__item {
          padding: 10px;
          transition: background-color 0.3s;
          display: flex;
          justify-content: space-between;
          align-items: center;

          .select-container__body__right__content__item__label {
            cursor: pointer;

            span:first-child {
              margin-right: 5px;
            }
          }

        }
      }
    }
  }
}

</style>
